package user_assets

import (
	"context"
	"fmt"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/logic/withdraw"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/service/setting_config"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/assets-api/pkg/common"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/base-common/pkg/xcode"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
)

type UserInsertBankInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// user-assets
func NewUserInsertBankInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserInsertBankInfoLogic {
	return &UserInsertBankInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserInsertBankInfoLogic) UserInsertBankInfo(req *types.UserInsertBankInfoRequest) (resp *types.UserInsertBankInfoResponse, err error) {
	userId := headInfo.GetTokenUid(l.ctx)
	if userId == 0 {
		return &types.UserInsertBankInfoResponse{
			IsInsert: false,
		}, xcode.UserNotFound
	}

	if err = l.verifyUseBankNum(userId); err != nil {
		return &types.UserInsertBankInfoResponse{
			IsInsert: false,
		}, err
	}

	in := &rpc.UserBankInfoInsertRequest{
		UserId:     userId,
		Username:   req.UserName,
		CardNumber: req.CardNum,
		IfscCode:   req.IFSCCode,
		Phone:      req.Phone,
		BankId:     req.BankId,
		Province:   req.Province,
		City:       req.City,
		BranchBank: req.BranchBank,
	}
	if withdraw.IsOpen(l.svcCtx, l.ctx, common.Card2Mail, "status") == 1 {
		in.Email = req.Email
	}
	_, err = l.svcCtx.AssetsRpc.UserChannel.UserBankInsert(l.ctx, in)

	if err != nil {
		return &types.UserInsertBankInfoResponse{
			IsInsert: false,
		}, err
	}
	return &types.UserInsertBankInfoResponse{
		IsInsert: true,
	}, err
}

func (l *UserInsertBankInfoLogic) verifyUseBankNum(userId int64) error {
	listRes, err := l.svcCtx.AssetsRpc.UserChannel.UserBankCount(l.ctx, &rpc.UserBankCountRequest{
		UserId: userId,
	})
	if err != nil {
		logc.Error(l.ctx, err)
		return err
	}

	userId = headInfo.GetTokenUid(l.ctx)

	limit := setting_config.GetBankCount(l.ctx, l.svcCtx.CommonSettingRpc)
	if limit == 0 || listRes.Count < limit {
		return nil
	}

	return xcode.New(http.StatusBadRequest, fmt.Sprintf("User bank num must less %d", limit))
}
